#include "articlecontent.h"

#include <QDebug>

ArticleContent::ArticleContent(Article* _article)
    :m_article(_article)
{
    parseData();
}


void ArticleContent::parseData()
{
    QList < int > listPosition = QList < int >();
    QString m_textContent = m_article->content();
    m_listData.clear();

    QString subText = "<img src";
    int index = m_textContent.indexOf(subText, 0);

    while (index != -1) {
        listPosition.append(index);

        index = m_textContent.indexOf(subText, index + 1);
    }

    if (listPosition.length() == 0) {
        m_listData.append(TextData(TextData::Text, m_textContent));
    } else {

        QString textData = m_textContent.mid(0, listPosition.at(0));
        textData.append("</body>");
        m_listData.append(TextData(TextData::Text, textData));

//        qDebug() << "===========================first Text :" << textData;

        for (int i=0 ; i < listPosition.length(); i++) {
            QString subImage = "/>";

            int indexImageStart = listPosition.at(i);
            int indexImageLast = m_textContent.indexOf(subImage, indexImageStart) + subImage.length();

            if (indexImageLast !=  -1) {
                QString imageHtml = m_textContent.mid(indexImageStart, indexImageLast - indexImageStart);
                // parsing to find link Image
                QString subImgFirst = "http";
                QString subImgLast = "'";
                int indexImageStartSub = imageHtml.indexOf(subImgFirst, 0);
                int indexImageLastSub = imageHtml.indexOf(subImgLast, indexImageStartSub);

                QString httpImage = imageHtml.mid(indexImageStartSub, indexImageLastSub - indexImageStartSub);

                m_listData.append(TextData(TextData::Image, httpImage));

//                qDebug() << "===========================Image data :" << httpImage;
            }


            int indexTextFirst = indexImageLast;
            int indexTextLast;
            if (i == listPosition.length() -1) {// het Image
                indexTextLast = m_textContent.length();
            } else {
                indexTextLast = listPosition.at(i + 1);
            }

            textData = "<body ";
            int Lenght = indexTextLast - indexTextFirst;
            QString text = m_textContent.mid(indexTextFirst , Lenght);
            textData = textData.append(text);
            if (i != listPosition.length() -1) {
                textData.append("</body>");
            }

//            qDebug() << "=========================== indexTextFirst" <<indexTextFirst;
//            qDebug() << "=========================== indexTextLast" <<indexTextLast;
//            qDebug() << "=========================== Lenght" <<Lenght;
//            qDebug() << "===========================TextData : " << textData;

            m_listData.append(TextData(TextData::Text, textData));
        }

    }
}
